package com.xincheng.shuimalong.activity.management;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.util.DateUtil;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.widget.StateButton;
import com.xincheng.library.widget.alertview.AlertView;
import com.xincheng.library.widget.pickerview.OptionsPickerView;
import com.xincheng.library.widget.pickerview.TimePickerView;
import com.xincheng.library.xswipemenurecyclerview.layoutmanager.FullyLinearLayoutManager;
import com.xincheng.library.xswipemenurecyclerview.recycler.MRecyclerView;
import com.xincheng.library.xswipemenurecyclerview.widget.DividerListItemDecoration;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.BaseActivity;
import com.xincheng.shuimalong.activity.config.InsuranceCompanyActivity;
import com.xincheng.shuimalong.activity.config.VciListActivity;
import com.xincheng.shuimalong.adapter.config.VciTypeSelectAdapter;
import com.xincheng.shuimalong.api.AppUrl;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.PostParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.Constant;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.entity.config.CommonConfig;
import com.xincheng.shuimalong.entity.config.District;
import com.xincheng.shuimalong.entity.config.RegionData;
import com.xincheng.shuimalong.entity.config.VciType;
import com.xincheng.shuimalong.entity.customer.Customer;
import com.xincheng.shuimalong.listener.ItemButtonClickListener;
import com.xincheng.shuimalong.util.BitmapUtil;
import com.xincheng.shuimalong.util.ConfigUtil;
import com.xincheng.shuimalong.util.ShowActivity;
import com.xincheng.shuimalong.view.picker.AreaPickerView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by 许浩 on 2017/7/1.
 */

public class InsuranceActivity extends BaseActivity {
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.rl_city)
    RelativeLayout rlCity;
    @BindView(R.id.tv_insurance)
    TextView tvInsurance;
    @BindView(R.id.rl_insurance)
    RelativeLayout rlInsurance;
    @BindView(R.id.switch_tci)
    SwitchCompat switchTci;
    @BindView(R.id.add_business_insurance)
    ImageView addBusinessInsurance;
    @BindView(R.id.btn_commit_message)
    StateButton btnCommitMessage;
    @BindView(R.id.tv_insurance_car_date)
    TextView tvInsuranceCarDate;
    @BindView(R.id.tv_insurance_date)
    TextView tvInsuranceDate;
    @BindView(R.id.policy_vci_select_mrv)
    MRecyclerView mVciSelectRv;
    private AreaPickerView mAreaPickerView;
    private TimePickerView timePickerView, timePickerView2;
    private ArrayList<VciType> mVciTypes;

    private VciTypeSelectAdapter mAdapter;

    private Customer data;
    private CommonConfig company;
    private String mToken;

    private String idCardPhoto1 = "", idCardPhoto2 = "", dlPhoto1 = "", dlPhoto2 = "";
    private String orgPhoto = "", orgNo = "";

    @Override
    public int getLayoutResId() {
        return R.layout.activity_insurance_layout;
    }

    @Override
    public void initData() {
        initTitleBar(getString(R.string.insurance_name));
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            data = bundle.getParcelable(IntentKey.CUSTOMER);
        }
        initVciTypes();
        mVciSelectRv.setLayoutManager(new FullyLinearLayoutManager(this));
        mVciSelectRv.addItemDecoration(new DividerListItemDecoration(this));
        mAdapter = new VciTypeSelectAdapter(this, mVciTypes);
        mVciSelectRv.setAdapter(mAdapter);
        mToken = PrefUtil.getString(this, PrefKey.TOKEN, "");
        initPickerView();
        initTimePicker();
        initTimePicker2();
        initPhoto();
    }

    private void initPhoto() {
        Glide.with(this).asBitmap().load(data.getIdcartd1_photo()).into(new MyBitmapTarget(1));
        Glide.with(this).asBitmap().load(data.getIdcartd2_photo()).into(new MyBitmapTarget(2));
        Glide.with(this).asBitmap().load(data.getD1_photo()).into(new MyBitmapTarget(3));
        Glide.with(this).asBitmap().load(data.getD2_photo()).into(new MyBitmapTarget(4));
    }

    private void initVciTypes() {
        if (mVciTypes == null) {
            mVciTypes = new ArrayList<>();
            List<VciType> list = ConfigUtil.getVciTypes(this);
            for (int i = 0; i < Constant.VCITPE_SELECT_SIZE_DEFAULT; i++) {
                VciType vciType = list.get(i);
                vciType.setOption(vciType.getOptions().get(vciType.getSelectOptionIndex()));
                if (vciType.getId() == 1) {
                    vciType.setNdis(true);
                }
                mVciTypes.add(vciType);
            }
        }
    }

    @Override
    public void addListener() {
        mAdapter.setItemButtonClickListener(new MyItemButtonClickListener(this));
    }

    private void initPickerView() {
        List<RegionData> provinceList = ConfigUtil.getRegionDataList(this, PrefKey.PROVINCE_LIST);
        mAreaPickerView = new AreaPickerView.Builder(this, new AreaPickerView.OnAreaSelectListener() {
            @Override
            public void onAreaSelect(RegionData province, RegionData city, District district, View v) {
                tvCity.setText(province.getName() + city.getName());
            }
        }).showDistrict(false).setTitleText(getString(R.string.area_select)).build();
        mAreaPickerView.setPicker(provinceList);
    }

    private void initTimePicker() {
        timePickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                String dateStr = DateUtil.parseDate2(date);
                data.setTci_date(dateStr);
                tvInsuranceCarDate.setText(dateStr);
            }
        }).setTitleText(getString(R.string.input_date)).setLabel("年", "月", "日", "时", null, null)
                .setType(new boolean[]{true, true, true, true, false, false})
                .isCenterLabel(false).build();
    }

    private void initTimePicker2() {
        timePickerView2 = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                String dateStr = DateUtil.parseDate2(date);
                data.setVci_date(dateStr);
                tvInsuranceDate.setText(dateStr);
            }
        }).setTitleText(getString(R.string.input_date)).setLabel("年", "月", "日", "时", null, null)
                .setType(new boolean[]{true, true, true, true, false, false})
                .isCenterLabel(false).build();
    }

    @OnClick({R.id.rl_city, R.id.rl_insurance, R.id.add_business_insurance, R.id.btn_commit_message, R.id
            .tv_insurance_car_date, R.id.tv_insurance_date})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_city:
                if (mAreaPickerView != null) {
                    mAreaPickerView.show();
                }
                break;
            case R.id.tv_insurance_car_date:
                if (timePickerView != null) {
                    timePickerView.show();
                } else {
                    initTimePicker();
                }
                break;
            case R.id.tv_insurance_date:
                if (timePickerView2 != null) {
                    timePickerView2.show();
                } else {
                    initTimePicker2();
                }
                break;
            case R.id.rl_insurance:
                Bundle extras1 = new Bundle();
                if (company != null) {
                    extras1.putParcelable(IntentKey.INSURANCE_COMPANY, company);
                }
                ShowActivity.showActivityForResult(this, InsuranceCompanyActivity.class, extras1,
                        RequestCodeKey.GO_INSURANCE_COMPAY_SELECT);
                break;
            case R.id.add_business_insurance:
                Bundle extras = new Bundle();
                if (!CommonUtil.isEmpty(mVciTypes)) {
                    extras.putParcelableArrayList(IntentKey.VCI_TYPE_LIST, mVciTypes);
                }
                ShowActivity.showActivityForResult(this, VciListActivity.class, extras,
                        RequestCodeKey.GO_SELECT_VCI_TYPE);
                break;
            case R.id.btn_commit_message:
                if (checkData()) {
                    if (switchTci.isChecked()) {
                        data.setTci_status(1);
                    } else {
                        data.setTci_status(0);
                    }
                    addCustomer();
                }
                break;
        }
    }

    private boolean checkData() {
        if (switchTci.isChecked() && CommonUtil.isEmpty(tvInsuranceCarDate)) {
            AlertView alertView = new AlertView(this, null, "交强险/车船税未填写完成", getString(R.string.cancel),
                    new String[]{getString(R.string.confirm)}, null,
                    AlertView.Style.Alert, null);
            alertView.show();
            return false;
        }
        if (CommonUtil.isEmpty(mVciTypes) || CommonUtil.isEmpty(tvInsuranceDate)) {
            AlertView alertView = new AlertView(this, null, "商业险未填写完成", getString(R.string.cancel),
                    new String[]{getString(R.string.confirm)}, null, AlertView.Style.Alert, null);
            alertView.show();
            return false;
        }
        return true;
    }

    private void addCustomer() {
        RetroSubscrube.getInstance().postSubscrube(AppUrl.ADD_CUSTOMER,
                PostParam.addCustomer(mToken, data.getPlate_no(), data.getCar_owner(), data.getMobile_phone(),
                        data.getCar_register_date(), data.getTransfer_car(), data.getTci_status(), data.getTci_date(),
                        data.getVci_date(), mVciTypes, idCardPhoto1, idCardPhoto2, dlPhoto1, dlPhoto2, orgPhoto, orgNo,
                        data.getCar_type(), data.getNew_car(),data.getOutput_volume(), data.getCurb_weight(), data.getCar_bak(),
                        data.getUseage(), data.getEngine_no(),data.getVin()),
                new BaseObserver(this, getString(R.string.loading_submit)) {

                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        showToast(msg);
                        Intent intent = new Intent();
                        intent.putExtra(IntentKey.SUCCESS, true);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCodeKey.GO_SELECT_VCI_TYPE:
                    mVciTypes = data.getParcelableArrayListExtra(IntentKey.VCI_TYPE_LIST);
                    for (int i = 0; i < mVciTypes.size(); i++) {
                        mVciTypes.get(i).setOption(mVciTypes.get(i).getOptions().get(1));
                    }
                    mAdapter.refreshData(mVciTypes);
                    break;
                case RequestCodeKey.GO_INSURANCE_COMPAY_SELECT:
                    company = data.getParcelableExtra(IntentKey.INSURANCE_COMPANY);
                    tvInsurance.setText(company.getName());
                    break;
            }
        }
    }

    private class MyItemButtonClickListener implements ItemButtonClickListener {
        private Context context;

        public MyItemButtonClickListener(Context context) {
            this.context = context;
        }

        @Override
        public void buttonClick(int clickId, int position) {
            VciType vciType = mAdapter.getItem(position);
            switch (clickId) {
                case R.id.vci_type_select_checked_tv:
                    vciType.ndisToggle();
                    mAdapter.notifyItemChanged(position);
                    break;
                case R.id.vci_type_select_option_tv:
                    initPicker(vciType, position);
                    break;
            }
        }

        private void initPicker(final VciType vciType, final int position) {
            final List<String> options = vciType.getOptions();
            OptionsPickerView pickerView = new OptionsPickerView.Builder(context, new OptionsPickerView
                    .OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    String option = options.get(options1);
                    vciType.setOption(option);
                    mAdapter.modifyItem(position, vciType);
                }
            }).setTitleText(vciType.getTitle()).build();
            pickerView.setPicker(options);
            pickerView.setSelectOptions(1);
            pickerView.show();
        }
    }

    private class MyBitmapTarget extends SimpleTarget<Bitmap> {
        private int status;

        public MyBitmapTarget(int status) {
            this.status = status;
        }

        @Override
        public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
            if (resource != null && resource.getWidth() > Constant.UPLOAD_IMAGE_SIZE_DEFAULT) {
                Bitmap bitmap = BitmapUtil.zoomImg(resource, Constant.UPLOAD_IMAGE_SIZE_DEFAULT);
                switch (status) {
                    case 1:
                        idCardPhoto1 = BitmapUtil.bitmapToBase64(bitmap);
                        break;
                    case 2:
                        idCardPhoto2 = BitmapUtil.bitmapToBase64(bitmap);
                        break;
                    case 3:
                        dlPhoto1 = BitmapUtil.bitmapToBase64(bitmap);
                        break;
                    case 4:
                        dlPhoto2 = BitmapUtil.bitmapToBase64(bitmap);
                        break;
                }
            }
        }
    }
}
